define(['config', 'text!app/module/system/addMaterialPurchase.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
             mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_arr = new Array();

    var purchaseSingleNo = Public.getRequestParam("purchaseSingleNo");

    var model = avalon.define({
        $id: "addMaterialPurchase",
        // 查询条件
        query: {},
        arsUnit: [
            {
                key: "件",
                val: '011'
            }
        ],
        materialPurchaseInfo: {
            id: "",
            uuid: "",
            purchaseSingleNo: "",//采购单号
            supplier: "",//供应商
            // createBy: "",//创建人
            // createDate: "",//创建日期
            status: "",//状态
            totalQuantity:"",//总数量
            amount:""//总金额

        },
        materialsPurchaseDetail: {
            id: "",
            goodsUuid: "",
            purchaseSingleNo: "",
            name: "",
            model: "",
            unit: "",
            unitPrice: "",
            currency: "",
            taxRate: "",
            totalQuantity: "",
            amount: "",
            color: ""
        },

        statusArr: [],
        selected: [],
        roles: [],

        init: function () {
            model.initPage();
            model.addEvent();
        },
        initPage: function () {
            function t(val, opt, row) {


                var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';

                return html_con;
            }

            if (!purchaseSingleNo) {
                $.ajax({
                    type: "POST",
                    url: "/api/materialsPurchase/getPurchaseSingleNo",
                    success: function (data) {
                        model.initmaterialPurchase();
                        model.materialPurchaseInfo.purchaseSingleNo = data;
                        if( model.materialPurchaseInfo.status>=10){
                            $("#save").css("display","none");
                        }
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " + responseData);
                    }
                });
            } else {
                $.ajax({
                    type: "POST",
                    url: "/api/materialsPurchase/findByPurchaseSingleNo",
                    data: {
                        "page": 1,
                        "rows": 1,
                        "purchaseSingleNo": purchaseSingleNo

                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    success: function (data) {
                        console.log("[data]", data);
                        model.initmaterialPurchase();
                        model.materialPurchaseInfo = data;
                        if( model.materialPurchaseInfo.status>=10){
                            $("#save").css("display","none");
                        }

                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " + JSON.stringify(responseData));
                    }
                });
                $.ajax({
                    type: "POST",
                    url: "/api/materialsPurchase/findDetailByPurchaseSingleNo",
                    data: {
                        "page": 1,
                        "rows": 1,
                        "purchaseSingleNo": purchaseSingleNo

                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    success: function (data) {
                        console.log("[data]", data);
                        grid_arr = data;
                        console.log('[grid_arr]', grid_arr);
                        model.reLoadGrid();

                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " +JSON.stringify(responseData) );
                    }
                });
            }
            $("#grid").jqGrid({
                datatype: "local",
                data: grid_arr,
                colModel: [{
                    name: "operating",
                    label: "操作",
                    width: '5%',
                    formatter: t,
                },
                    {
                        name: "name",
                        label: "品名",
                        width: '8%'
                    },
                    {
                        name: "goodsUuid",
                        label: "uuid",
                        width: '8%',
                        hidden:true
                    },
                    {
                        name: "model",
                        label: "规格",
                        width: '10%'
                    },
                    {
                        name: "unitPrice",
                        label: "单价",
                        width: '13%'
                    },
                    {
                        name: "color",
                        label: "颜色",
                        width: '13%'
                    },
                    {
                        name: "totalQuantity",
                        label: "数量",
                        width: "7%"
                    },
                    {
                        name: "unit",
                        label: "计量单位",
                        width: '10%'
                    },
                    {
                        name: "amount",
                        label: "总价",
                        width: '13%'
                    }
                ],
                page: 1,
                // rowNum: 10,
                // rowList: [10, 20, 30],
                height: '250px',
                autowidth: true,
                // pager: '#page',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc"
            });
        },
        reLoadGrid: function () {
            $("#grid").jqGrid("setGridParam", {
                datatype: "local",
                data: grid_arr,
                page: 1,
            }).trigger("reloadGrid");
        },
        //添加或更新
        add: function () {
            model.initmaterialPurchaseDetail();
            model.materialsPurchaseDetail.purchaseSingleNo = model.materialPurchaseInfo.purchaseSingleNo;
            /**自动匹配商品*/
            $("#name").autocomplete({
                serviceUrl: "/api/materialsPurchase/getGoodsByName",
                paramName: "name",
                minLength: 0,
                // 其他ajax配置
                ajaxSettings: {
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: '无匹配项',
                onSearchStart: function (query) {
                },
                transformResult: function (response) {
                    var obj = $.parseJSON(response);
                    console.log('obj.data', obj);
                    return {
                        suggestions: $.map(obj.data, function (data) {
                            return {
                                value: "品名：" + data.name,
                                data: data
                            };
                        })
                    };
                },
                onSelect: function (suggestion) {
                    console.log('[suggestion.data]', suggestion.data);
                    model.materialsPurchaseDetail.name = suggestion.data.name;
                    model.materialsPurchaseDetail.model = suggestion.data.model;
                    model.materialsPurchaseDetail.unit = suggestion.data.unit;
                    model.materialsPurchaseDetail.unitPrice = suggestion.data.unitPrice;
                    model.materialsPurchaseDetail.currency = suggestion.data.currency;
                    model.materialsPurchaseDetail.taxRate = suggestion.data.taxRate;
                    model.materialsPurchaseDetail.color = suggestion.data.color;
                    model.materialsPurchaseDetail.goodsUuid = suggestion.data.uuid;
                },
                onSearchComplete: function (query, suggestions) {
                    $("div[data-index=0]").addClass("autocomplete-selected");
                }
            });
            dialog({
                title: '添加原料',
                content: $('#editGoodsDetail'),
                okValue: "确定",
                ok: function addRow() {
                    var rowData = model.materialsPurchaseDetail.$model;
                    var selectedId = $("#grid").jqGrid("getGridParam", "selrow");
                    var rowid = new Date().getTime();
                    rowData.id = new Date().getTime();
                    rowData.amount = rowData.unitPrice*rowData.totalQuantity;
                    if (selectedId) {
                        $("#grid").jqGrid("addRowData", rowid, rowData, "after", selectedId);
                    } else {
                        $("#grid").jqGrid("addRowData", rowid, rowData, "last");
                    }
                    grid_arr.push(rowData);
                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },

        edit: function (obj, t) {
            var id=$("#grid").jqGrid('getGridParam', 'selrow');
            model.materialsPurchaseDetail = $("#grid").jqGrid('getRowData', id);
            console.log(" model.materialsPurchaseDetail"+JSON.stringify(model.materialsPurchaseDetail) );
            /**自动匹配商品*/
            $("#name").autocomplete({
                serviceUrl: "/api/materialsPurchase/getGoodsByName",
                paramName: "name",
                minLength: 0,
                // 其他ajax配置
                ajaxSettings: {
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: '无匹配项',
                onSearchStart: function (query) {
                },
                transformResult: function (response) {
                    var obj = $.parseJSON(response);
                    console.log('obj.data', obj);
                    return {
                        suggestions: $.map(obj.data, function (data) {
                            return {
                                value: data.name,
                                data: data
                            };
                        })
                    };
                },
                onSelect: function (suggestion) {
                    model.materialsPurchaseDetail.name = suggestion.data.name;
                    model.materialsPurchaseDetail.model = suggestion.data.model;
                    model.materialsPurchaseDetail.unit = suggestion.data.unit;
                    model.materialsPurchaseDetail.unitPrice = suggestion.data.unitPrice;
                    model.materialsPurchaseDetail.currency = suggestion.data.currency;
                    model.materialsPurchaseDetail.taxRate = suggestion.data.taxRate;
                    model.materialsPurchaseDetail.color = suggestion.data.color;
                    model.materialsPurchaseDetail.goodsUuid = suggestion.data.uuid;
                },
                onSearchComplete: function (query, suggestions) {
                    $("div[data-index=0]").addClass("autocomplete-selected");
                }
            });
            dialog({
                title: '编辑商品信息',
                content: $('#editGoodsDetail'),
                okValue: "确定",
                ok: function addRow() {
                    var rowData = model.materialsPurchaseDetail.$model;
                    if(model.isEmpty(rowData.name.trim(),"品名不能为空!")
                            && model.isEmpty(rowData.totalQuantity.trim(),"数量不能为空!")){
                        for (var i = 0; i < grid_arr.length; i++) {
                            if (grid_arr[i].id == t) {
                                rowData.purchaseSingleNo = model.materialPurchaseInfo.purchaseSingleNo;
                                rowData.amount = rowData.unitPrice*rowData.totalQuantity;
                                rowData.id = new Date().getTime();
                                grid_arr[i] = rowData;
                                model.reLoadGrid();
                            }
                        }
                    }  else {
                        return false;
                    }

                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },   isEmpty: function (value, alerttxt) {
            if (value == null || value == "") {
                Public.tips({
                    type: 2,
                    content: alerttxt
                });
                return false;
            }
            else {
                return true;
            }
        },


        /**删除商品*/
        del: function (id) {
            dialog({
                title: "确认操作",
                content: "确定删除？ 此操作不可恢复！",
                okValue: "确定",
                ok: function () {
                    for (var i = 0; i < grid_arr.length; i++) {
                        if (grid_arr[i].id == id) {
                            grid_arr.splice(i, 1);
                            $('#grid').jqGrid('delRowData', id);
                        }
                    }
                    model.reLoadGrid();

                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },
        addEvent: function () {
            //返回
            $(".fr").on("click", "#close", function (e) {
                console.log('1111111111111111111111');
                top.topManager.closePage();
                top.topManager.openPage({
                    id: "materialPurchaseManage",
                    title: "原料采购",
                    href: 'index.html#!/117',
                    reload: true
                })
            });
            //添加商品
            $(".grid-wrap").on("click", "#addGoods", function (e) {
                model.add();
            });
            $(".grid-wrap").on("click", ".fa-edit", function (e) {
                var t = $(this).parent().data("id");
                console.log('grid_arr', grid_arr);
                // if (grid_arr.length == 0) {
                //     model.anotherEdit($("#grid").getRowData(t), t);
                // } else {
                    model.edit($("#grid").getRowData(t), t);
                // }
            });
            //提交表单
            $(".fr").on("click", "#save", function (e) {
                for (var i = 0; i < grid_arr.length; i++) {
                    grid_arr[i].id = "";
                }
                var purchaseOrder = {
                    materialsPurchase: model.materialPurchaseInfo,
                    materialsPurchaseDetailList: grid_arr
                };
                $.ajax({
                    contentType: "application/json;charset=utf-8",
                    type: "POST",
                    url: "/api/materialsPurchase/savePurchaseOrder",
                    data: JSON.stringify(purchaseOrder),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    success: function (data) {
                        if(data.success){
                            dialog({
                                            title: "提示",
                                            content: "保存成功！",
                                            okValue: "确定",
                                      	 ok: function (){
                                      		 // location.replace('index.html#!/117');
                                      	 }
                                   	 }).showModal();
                        }else{
                            alert("Failed: " + JSON.stringify(data.data.msg));
                        }
                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " + JSON.stringify(responseData));
                    }
                });
            });
            $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                var selectedId = $("#grid").jqGrid("getGridParam", "selrow");
                model.del(selectedId);
            });
        },
        initmaterialPurchase: function () {
            model.materialPurchaseInfo = {
                id: "",
                uuid: "",
                purchaseSingleNo: "",//采购单号
                supplier: "",//供应商
                // createBy: "",//创建人
                // createDate: "",//创建日期
                status: "",//状态
                totalQuantity:"",//总数量
                amount:""//总金额
            }
        },
        initmaterialPurchaseDetail: function () {
            model.materialsPurchaseDetail = {
                id: "",
                goodsUuid: "",
                purchaseSingleNo: "",
                name: "",
                model: "",
                unit: "",
                unitPrice: "",
                currency: "",
                taxRate: "",
                totalQuantity: "",
                amount: "",
                color: ""

            }
        }


    });

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {
        } // 切换菜单时销毁原来的view
    };
    return viewmod;


});